OPTION(AWS_SDK_EXTERNAL_PROJECT  "Allow to download and build AWS C++ SDK" OFF)
INCLUDE(aws_sdk)
INCLUDE(ExternalProject)

GET_PROPERTY(SDK_LIBS GLOBAL PROPERTY AWS_SDK_LIBS)
LIST(LENGTH SDK_LIBS SDK_LIBS_COUNT)
IF(SDK_LIBS_COUNT EQUAL 0)
  RETURN()
ENDIF()

CHECK_AWS_SDK(RETVAL REASON)
IF(NOT RETVAL)
  MESSAGE(FATAL_ERROR 
   "AWS C++ will not be built (${REASON}), but dependency on following components is found ${SDK_LIBS}.
   Use CHECK_AWS_SDK() function before trying to build with SDK components")
ENDIF()
 

SET(byproducts)

FOREACH(lib ${SDK_LIBS} core)
  SET(lib aws-cpp-sdk-${lib})
  ADD_LIBRARY(${lib} STATIC IMPORTED GLOBAL)
  ADD_DEPENDENCIES(${lib} aws_sdk_cpp)
  
  SET (loc "${CMAKE_CURRENT_BINARY_DIR}/aws_sdk_cpp/lib/${CMAKE_STATIC_LIBRARY_PREFIX}${lib}${CMAKE_STATIC_LIBRARY_SUFFIX}")
  IF(CMAKE_VERSION VERSION_GREATER "3.1")
    SET(byproducts ${byproducts} BUILD_BYPRODUCTS ${loc})
  ENDIF()
  SET_TARGET_PROPERTIES(${lib} PROPERTIES IMPORTED_LOCATION ${loc})
ENDFOREACH()

# To be compatible with older cmake, we use older version of the SDK
IF(CMAKE_VERSION LESS "3.0")
  SET(GIT_TAG "1.0.8")
ELSE()
  SET(GIT_TAG "1.8.29")
ENDIF()

IF(MSVC_CRT_TYPE MATCHES "/MD")
  SET(FORCE_SHARED_CRT ON)
ELSE()
  SET(FORCE_SHARED_CRT OFF)
ENDIF()

LIST(REMOVE_DUPLICATES SDK_LIBS)
STRING( REPLACE ";" "!" SDK_LIBS_STR "${SDK_LIBS}")
#MESSAGE("SDK_LIBS_STR=${SDK_LIBS_STR}")

ExternalProject_Add(
  aws_sdk_cpp
  GIT_REPOSITORY "https://github.com/awslabs/aws-sdk-cpp.git"
  GIT_TAG ${GIT_TAG}
  UPDATE_COMMAND ""
  SOURCE_DIR "${CMAKE_CURRENT_BINARY_DIR}/aws-sdk-cpp"
  LIST_SEPARATOR !
  ${byproducts}
  CMAKE_ARGS
    -DBUILD_ONLY=${SDK_LIBS_STR}
    -DBUILD_SHARED_LIBS=OFF
    -DFORCE_SHARED_CRT=${FORCE_SHARED_CRT}
    -DENABLE_TESTING=OFF
    "-DCMAKE_CXX_FLAGS_DEBUG=${CMAKE_CXX_FLAGS_DEBUG} ${PIC_FLAG}"
    "-DCMAKE_CXX_FLAGS_RELWITHDEBINFO=${CMAKE_CXX_FLAGS_RELWITHDEBINFO} ${PIC_FLAG}"
    "-DCMAKE_CXX_FLAGS_RELEASE=${CMAKE_CXX_FLAGS_RELEASE} ${PIC_FLAG}"
    "-DCMAKE_CXX_FLAGS_MINSIZEREL=${CMAKE_CXX_FLAGS_MINSIZEREL} ${PIC_FLAG}"
    "-DCMAKE_C_COMPILER=${CMAKE_C_COMPILER}"
    "-DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER}"
    ${EXTRA_SDK_CMAKE_FLAGS}
    -DCMAKE_INSTALL_PREFIX=${CMAKE_CURRENT_BINARY_DIR}/aws_sdk_cpp
    -DCMAKE_INSTALL_LIBDIR=lib
    TEST_COMMAND ""
)
SET_TARGET_PROPERTIES(aws_sdk_cpp PROPERTIES EXCLUDE_FROM_ALL TRUE)
